package com.study.forkjoin;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.concurrent.RecursiveTask;

class MyTask extends RecursiveTask<Integer> {

    // 拆分差值不能超过10，相加运算
    private static final Integer VALUE = 10;
    // 拆分开始值
    private int begin;
    // 拆分结束值
    private int end;
    // 返回结果
    private int result;

    public MyTask(int begin, int end) {
        this.begin = begin;
        this.end = end;
    }

    /**
     * @description: 拆分合并过程
     * @param
     * @return java.lang.Integer
     * @author wanghao
     * @date 2022/1/5  16:46
     * @version v1.0
     * @change [修改时间] [修改者]@[版本号] [修改内容说明]
     */
    @Override
    protected Integer compute() {
        // 判断两个数差值是否小于等于10
        if ((end-begin) <= VALUE) {
            // 相加操作
            for (int i = begin; i <= end; i++) {
                result += i;
            }
        } else {
            // 进一步拆分
            int middle = (begin + end) / 2;
            // 拆分左边
            MyTask task01 = new MyTask(begin, middle);
            MyTask task02 = new MyTask(middle+1, end);
            // 调用方法拆分
            task01.fork();
            task02.fork();
            // 合并结果
            result = task01.join() + task02.join();
        }
        return result;
    }
}

/**
 * @author wanghao
 * @version v1.0
 * @description: 分支合并框架
 * @date 2022/1/5 16:10
 * @change [修改时间] [修改者]@[版本号] [修改内容说明]
 */
public class ForkJoinDemo {

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        MyTask myTask = new MyTask(0,100);
        ForkJoinPool forkJoinPool = new ForkJoinPool();
        ForkJoinTask<Integer> forkJoinTask = forkJoinPool.submit(myTask);
        System.out.println(forkJoinTask.get());
        forkJoinPool.shutdown();
    }
}
